<?php


namespace App\Services\Base;


use App\Constants\AuthType;
use App\Constants\VerifyCodeType;
use App\Exceptions\ApiException;
use App\Models\User;
use App\Traits\BaseTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

class CommonService
{
    use BaseTrait;

    public function requestCodeKey($params)
    {
        if (!key_exists('key', $params) ||    //key
            !key_exists('type', $params)        //类型
        ) {
            throw new \Exception('', 408);
        }

        $key = $params['key'];
        $info = CacheService::get(R_VERIFY_KEY . $key);
        if (!$info) {
            throw new \Exception('', 418);  //认证失效
        }

        $info = json_decode($info, true);
        $params['register_type'] = $info['register_type'] ?? User::DEFAULT_REGISTER_TYPE;
        $params['device_id'] = $info['device_id'];
        $params['name'] = $info['name'];

        return $this->requestCode($params);
    }

    //请求验证码
    public function requestCode($params)
    {
        // !key_exists('register_type', $params) ||    //1邮箱 2手机
        // !key_exists('device_id', $params) ||    //设备id
        if (
            !key_exists('type', $params) ||        //类型
            !key_exists('name', $params)           //手机号码或者邮箱
        ) {
            throw new \Exception('', 408);
        }

        $code_type = $params['register_type'] ?? User::DEFAULT_REGISTER_TYPE;
        $device_id = $params['device_id'] ?? User::DEFAULT_DEVICE_ID;
        $type = $params['type'];
        $name = $params['name'];
        $lang = $params['lang'];

        if (!key_exists($code_type, AuthType::$lib_check_type)) {
            throw new \Exception('', 410);
        }

        if (!key_exists($type, VerifyCodeType::$lib_type)) {
            throw new \Exception('', 410);
        }

        HelpService::checkEmailOrPhone($name, $code_type);
        if ($type == VerifyCodeType::TYPE_FORGET_PASSWORD) { //忘记密码
            switch ($type) {
                case AuthType::CHECK_EMAIL:
                    User::findUser($params['name'], 'email');
                    break;
                case AuthType::CHECK_PHONE:
                    User::findUser($params['name'], 'phone');
                    break;
            }
        }

        $title = "base";
        $service = new CodeService();
        return $service->send($name, $device_id, $name, $type, $title, $code_type, 'aliyun', $lang);

    }

    /**
     * 获取列表
     * @param $selfModel
     * @param array $params
     * @param string $field
     * @param array $joinTable
     * @param string $joinField
     * @param bool $all
     * @return array
     * @throws \App\Exceptions\CustomException
     */
    public function getListById($selfModel, $params = [], $field = "*", $joinTable = [], $joinField = "", $all = false)
    {
        $limit = 2;
        $result = [];
        try {
            $directions = [1, 2, 3]; //1大于id 2小于id 3最新
            if (!$all) {
                if (!isset($params['direction']) || !$params['direction'] || !in_array($params['direction'], $directions)) {
                    throw new \Exception("方向有误", COMMON_MESSAGE);
                }
            }

            if ($joinTable) {
                $model = $selfModel->orderBy($selfModel->getTable() . '.id', 'desc');
            } else {
                $model = $selfModel->orderBy('id', 'desc');
            }

            if (!$all) {
                if ($params['direction'] == 1) {
                    if (!$params['id']) {
                        throw new \Exception("id有误", COMMON_MESSAGE);
                    }
                    if ($joinTable) {
                        list($a, $b, $c, $d) = $joinTable;
                        $model = $model->where('id', '>', $params['id'])->leftJoin($a, $b, $c, $d);
                    } else {
                        $model = $model->where('id', '>', $params['id']);
                    }
                } else if ($params['direction'] == 2) {
                    if (!$params['id']) {
                        throw new \Exception("id有误", COMMON_MESSAGE);
                    }
                    if ($joinTable) {
                        list($a, $b, $c, $d) = $joinTable;
                        $model = $model->where('id', '<', $params['id'])->leftJoin($a, $b, $c, $d);
                    } else {
                        $model = $model->where('id', '<', $params['id']);
                    }
                } else {
                    if ($joinTable) {
                        list($a, $b, $c, $d) = $joinTable;
                        $model = $model->leftJoin($a, $b, $c, $d);
                    }
                }
                if ($joinField) {
                    $select = array_merge($field, $joinField);
                    $result = $model->select($select)->limit($limit)->get()->toArray();
                } else {
                    $result = $model->select($field)->limit($limit)->get()->toArray();
                }
            } else {
                $result = $model->select($field)->get()->toArray();
                $result = array_column($result, $field);
            }

            return $result;
        } catch (\Exception $e) {
            $this->throwError($e->getCode(), $e->getMessage());
        }
    }

}
